package com.lx.boot.web.valid;

import com.lx.annotation.Note;
import com.lx.boot.OS;
import com.lx.util.LX;
import jakarta.validation.*;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Set;


@Data
@AllArgsConstructor
public class Validate{
    @Note("注解自定义参数!")
    private String value;

    @Note("注解扩展参数!")
    private String[] ext;

    @Note("实际数据!")
    private Object object;

    @Note("注解验证上下文")
    private ConstraintValidatorContext constraintValidatorContext;

    @Note("修改返回信息")
    public void setMessage(String msg){
        this.constraintValidatorContext.disableDefaultConstraintViolation();//禁用默认的message的值
        this.constraintValidatorContext.buildConstraintViolationWithTemplate(msg).addConstraintViolation();
    }

    @Note("判断实际数据是否不为空!")
    public boolean isNotEmpty(){
        return LX.isNotEmpty(object);
    }

    @Note("判断实际数据是否为null")
    public boolean objIsNull(){
        return object == null;
    }

    @Note("判断实际数据是否不为null")
    public boolean objIsNotNull(){
        return object != null;
    }

    @Note("获取实际数据")
    public <T>T getObject(){
        return (T)object;
    }

    private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    @Note("参数校验")
    public static <T> void validate(T object, Class<?>... groups) {
        Set<ConstraintViolation<T>> validate =validator.validate(object, groups);
        if (!validate.isEmpty()) {
            throw new ConstraintViolationException(validate);
        }
    }
}